package com.net.tomcat5.Servlet3;
import com.net.tomcat5.Request;
import com.net.tomcat5.Response;

import java.io.IOException;
import java.net.Socket;

/**
 * 一个请求与响应 就一个此对象
 *
 * @author jiangbang
 * @date 2016/8/25
 */
public class Dispatcher implements Runnable {
    private Socket client;
    private Request request;
    private Response response;
    private int code =200;

    public Dispatcher(Socket client) {
        this.client = client;
        try {
            request = new Request(client.getInputStream());
            response = new Response(client.getOutputStream());
        } catch (IOException e) {
            code = 500;
           return;
        }
    }

    @Override
    public void run() {
        try {
        Servlet servlet = WebApp.getServlet(request.getUrl());
        if(null==servlet){
            this.code=404; //找不到处理
        }
        servlet.service(request,response);
        response.pushToClient(code); //推送到客户端
        } catch (IOException e) {
            this.code=500;
        }

    }
}
